package xxljob

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/xxl-job/xxl-job-executor-go"
	"uni-crawl-frame/service/configservice"
)

type XxlJobWrapper struct {
	exec xxl.Executor
}

func (jobWrapper *XxlJobWrapper) Init() {
	jobWrapper.exec = xxl.NewExecutor(
		xxl.ServerAddr(configservice.GetString("xxl.job.admin.addresses")),
		xxl.AccessToken(configservice.GetString("xxl.job.accessToken")),      //请求令牌(默认为空)
		xxl.ExecutorIp(configservice.GetString("xxl.job.executor.ip")),       // 可自动获取
		xxl.ExecutorPort(configservice.GetString("xxl.job.executor.port")),   // 默认9999（非必填）
		xxl.RegistryKey(configservice.GetString("xxl.job.executor.appname")), //执行器名称
		xxl.SetLogger(&logger{}), //自定义日志
	)
	jobWrapper.exec.Init()
	jobWrapper.exec.Use(customMiddleware)

	// 设置日志查看handler
	jobWrapper.exec.LogHandler(customLogHandle)
}

func (jobWrapper *XxlJobWrapper) RegTask(name string, task xxl.TaskFunc) {
	jobWrapper.exec.RegTask(name, task)
}

func (jobWrapper *XxlJobWrapper) Run() {
	err := jobWrapper.exec.Run()
	if err != nil {
		panic(err)
	}
}

// 自定义日志处理器
func customLogHandle(req *xxl.LogReq) *xxl.LogRes {
	return &xxl.LogRes{Code: xxl.SuccessCode, Msg: "", Content: xxl.LogResContent{
		FromLineNum: req.FromLineNum,
		ToLineNum:   2,
		LogContent:  "这个是自定义日志handler",
		IsEnd:       true,
	}}
}

// xxl.Logger接口实现
type logger struct{}

func (l *logger) Info(format string, a ...interface{}) {
	g.Log().Line().Info(gctx.GetInitCtx(), format, a)
}

func (l *logger) Error(format string, a ...interface{}) {
	g.Log().Line().Error(gctx.GetInitCtx(), format, a)
}

// 自定义中间件
func customMiddleware(tf xxl.TaskFunc) xxl.TaskFunc {
	return func(cxt context.Context, param *xxl.RunReq) string {
		g.Log().Line().Info(gctx.GetInitCtx(), "I am a middleware start")
		res := tf(cxt, param)
		g.Log().Line().Info(gctx.GetInitCtx(), "I am a middleware end")
		return res
	}
}
